package com.hall.item.item.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hall.item.item.pojo.ItemDoc;
import com.hall.item.item.pojo.RequestParams;
import com.hall.item.item.service.SearchService;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private ItemClient itemClient;

    @Override
    public void insertById(Long id) {
        try {
            //0.根据id查询酒店数据
            Item item = itemClient.getById(id);
            ItemDoc itemDoc = new ItemDoc(item);
            //1.准备Request对象
            IndexRequest request = new IndexRequest("hmall").id(id.toString());
            //2.准备Json文档
            request.source(MAPPER.writeValueAsString(itemDoc), XContentType.JSON);
            //3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            //1.准备Request
            DeleteRequest request = new DeleteRequest("hmall", id.toString());
            //2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public List<String> getSuggestion(String key) {
        try {
            //1.创建Request对象
            SearchRequest request = new SearchRequest("hmall");
            //2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion
                    ("suggestions",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .text(key)
                                    .skipDuplicates(true)
                                    .size(10)
                    ));
            //3.发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析结果
            Suggest suggest = response.getSuggest();
            /*
                CompletionSuggestion为
                Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>>
                的子类
             */
            //4.1根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            //4.2获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //4.3遍历
            List<String> list = options.stream().map(item -> {
                String text = item.getText().toString();
                return text;
            }).collect(Collectors.toList());
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            //1.创建Request对象
            SearchRequest request = new SearchRequest("hmall");
            //2.编写DSL
            //2.1query
            bulidBasicQuery(params, request);
            //2.2设置size
            request.source().size(0);
            //2.3聚合
            bulidAggregation(request);
            //3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //4.1根据分类名称，获取分类结果
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryList);
            //4.2根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PageDTO<ItemDoc> queryList(RequestParams params) {
        try {
            //1.创建Request对象
            SearchRequest request = new SearchRequest("hmall");
            //2.编写DSL
            //2.1query
            bulidBasicQuery(params, request);
            //2.2分页查询
            Integer page = params.getPage();
            Integer size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            //2.3sorted排序
            if ("sold".equals(params.getSortBy())) {
                request.source().sort("sold", SortOrder.DESC);
            }
            if ("price".equals(params.getSortBy())) {
                request.source().sort("price");
            }
            //3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析结果
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private PageDTO<ItemDoc> handleResponse(SearchResponse response) throws JsonProcessingException {
        // 4.解析响应
        SearchHits hits = response.getHits();
        // 4.1.获取总条数
        long total = hits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] searchHits = hits.getHits();
        // 4.3.遍历
        List<ItemDoc> list = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            //获取文档source
            String json = searchHit.getSourceAsString();
            //反序列化
            ItemDoc itemDoc = MAPPER.readValue(json, ItemDoc.class);
            //添加到集合中
            list.add(itemDoc);
        }
        // 4.4.封装返回
        return new PageDTO<ItemDoc>(total, list);
    }


    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //4.1根据聚合名称获取聚合的结果
        Terms commonTerms = aggregations.get(aggName);
        //4.2获取buckets
        List<? extends Terms.Bucket> buckets = commonTerms.getBuckets();
        //4.3遍历
        List<String> commonList = buckets.stream().map(item -> {
            //4.4获取key
            String key = item.getKeyAsString();
            return key;
        }).collect(Collectors.toList());
        return commonList;
    }

    private void bulidAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
    }

    private void bulidBasicQuery(RequestParams params, SearchRequest request) {
        //2.1创建BooleanQuery对象
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //2.2关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }

        //3.品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }

        //4.分类条件
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }


        //5.价格条件
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }

        //6.算分控制
        QueryBuilders.functionScoreQuery(
                // 原始查询，相关性算分的查询
                boolQuery,
                // function score的数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        // 其中的一个function score 元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }).boostMode(CombineFunction.MULTIPLY);

        HighlightBuilder builder = new HighlightBuilder().field("all");
        builder.preTags("<em>");
        builder.postTags("</em>");
        builder.requireFieldMatch(false);

        //7.放入source
        request.source().query(boolQuery)
                .highlighter(builder);
    }



}
